package com.qf.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.entity.Order;
import com.qf.entity.OrderDTO;
import com.qf.entity.OrderVO;
import com.qf.listener.OrderVODataListener;
import com.qf.service.OrderVOService;
import com.qf.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;

/**
 * 天--道--酬--勤
 *
 * @author LiangGaoQiang
 * @ClassName OrderVOController
 * @Date: 2025/5/1 21:02
 * @Description: 描述
 */


@RestController
@RequestMapping("/orderVo")
public class OrderVOController {

    @Autowired
    private OrderVOService orderVOService;
    private static final Logger logger = LoggerFactory.getLogger(OrderVOController.class);

    @GetMapping("/fuzzyQueryOrder")
    public R fuzzyQueryOrder(@Valid OrderDTO orderDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return R.error(bindingResult.getFieldError().getDefaultMessage());
        }

        try {
            // 使用logger记录日志信息
            logger.info("开始分页查询，pageNum: {}, pageSize: {}", orderDTO.getPageNum(), orderDTO.getPageSize());
            PageHelper.startPage(orderDTO.getPageNum(), orderDTO.getPageSize());
            List<OrderVO> orderVOList = orderVOService.fuzzyQueryOrder(orderDTO);
            logger.info("查询结果大小: {}", orderVOList.size());
            PageInfo<OrderVO> pageInfo = new PageInfo<>(orderVOList);
            return R.ok(pageInfo);
        } catch (Exception e) {
            logger.error("查询订单时发生错误", e);
            return R.error("查询订单时发生错误");
        }
    }


    @PostMapping("/addOrder")
    public R addOrder(@RequestBody Order order) {
        Boolean result = orderVOService.addOrder(order);
        if (result) {
            return R.ok();
        } else {
            return R.error("新增订单失败");
        }
    }

    @PostMapping("/updateOrder")
    public R updateOrder(@RequestBody Order order) {
        Boolean result = orderVOService.updateOrder(order);
        if (result) {
            return R.ok();
        } else {
            return R.error("更新订单失败");
        }
    }

    /**
     * 上传Excel文件
     */
    @PostMapping("/upload/excel")
    public R uploadExcel(MultipartFile file) {
        try {
            // 重点,此处第三个参数需要传入Service对象
            EasyExcel.read(file.getInputStream(), OrderVO.class, new OrderVODataListener(orderVOService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }
}

